<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="primary"
          class="handle-del mr10"
          @click="handleIncrease"
          v-if="bdmPermissions.includes('village:subdistrict:save')"
          >添加</el-button
        >
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        class="table"
        header-cell-class-name="table-header"
        border
      >
        <el-table-column label="区域">
          <template slot-scope="scope">
            <!--这里对等级进行循环，循环出相应的空格，在视图上来表示等级关系；减 1 是因为我们的等级是从1开始的-->
            <span
              class="space"
              v-for="i in scope.row.level - 1"
              :key="i"
            ></span>
            <i
              :class="{
                'el-icon-caret-right': !scope.row.show,
                'el-icon-caret-bottom': scope.row.show,
              }"
              @click="handleRow(scope.$index, scope.row)"
              v-if="scope.row.children"
            ></i>
            <!--当展开箭头不应该显示的时候，这里应该也要有相应的占位，不影响视图显示-->
            <span class="arrow-width" v-else></span>
            <span>{{ scope.row.area }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="left">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="bdmPermissions.includes('village:subdistrict:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="bdmPermissions.includes('village:subdistrict:delete')"
              >删除</el-button
            >
            <el-button
              type="text"
              v-if="
                scope.row.level <= 2 &&
                  bdmPermissions.includes('village:subdistrict:save')
              "
              @click.native.prevent="increaseRow(scope.$index, scope.row)"
              >新增</el-button
            >
            <el-button
              type="text"
              @click="handleStop(scope.$index, scope.row)"
              v-if="scope.row.enableStatus.toString() == 0"
              >停用</el-button
            >
            <el-button
              type="text"
              @click="handleEnable(scope.$index, scope.row)"
              v-if="scope.row.enableStatus.toString() == 1"
              >启用</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <!-- 编辑弹出框 -->
    <el-dialog
      :title="'编辑' + areaName"
      :visible.sync="editVisible"
      width="50%"
    >
      <el-form ref="form" :model="editForm" label-width="120px" :rules="rules">
        <el-form-item
          v-if="show2 && options.length !== 0"
          label="所属上一级"
          prop="id"
        >
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.area"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="areaName" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input v-model="editForm.memo"></el-input>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="enableStatus">
          <template>
            <el-radio v-model="editForm.enableStatus" label="0">启用</el-radio>
            <el-radio v-model="editForm.enableStatus" label="1">停用</el-radio>
          </template>
        </el-form-item> -->
        <!-- <el-form-item label="删除状态" prop="deleteStatus">
          <template>
            <el-radio v-model="editForm.deleteStatus" label="0">正常</el-radio>
            <el-radio v-model="editForm.deleteStatus" label="1">删除</el-radio>
          </template>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog
      :title="'新增' + areaName"
      :visible.sync="addVisible"
      width="50%"
    >
      <el-form ref="form" :model="addForm" label-width="120px" :rules="rules">
        <el-form-item
          v-if="show1 && options.length !== 0"
          label="所属上一级"
          prop="id"
        >
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.area"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="areaName" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input v-model="addForm.memo"></el-input>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="enableStatus">
          <template>
            <el-radio v-model="addForm.enableStatus" label="0">启用</el-radio>
            <el-radio v-model="addForm.enableStatus" label="1">停用</el-radio>
          </template>
        </el-form-item> -->
        <!-- <el-form-item label="删除状态" prop="deleteStatus">
          <template>
            <el-radio v-model="addForm.deleteStatus" label="0">正常</el-radio>
            <el-radio v-model="addForm.deleteStatus" label="1">删除</el-radio>
          </template>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveIncrease">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  name: "basicdatamanage",
  data() {
    return {
      options: [],
      options1: [],

      value: "",
      bdmPermissions: [],
      editVisible: false,
      addVisible: false,
      show1: false,
      show2: false,
      query: {
        address: "",
        name: "",
        pageIndex: 1,
        pageSize: 20,
      },
      pageTotal: 0,
      form: {
        area: "",
      },
      addForm: {
        name: "",
        memo: "",
        subLevel: "",
        // enableStatus: "0",
        // deleteStatus: "0"
      },
      editForm: {
        id: "",
        name: "",
        memo: "",
        parentId: "",
        subLevel: "",
        enableStatus: "",
        // enableStatus: "0",
        // deleteStatus: "0"
      },
      rules: {
        id: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        name: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        memo: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        // required: [
        //   { required: true, message: "必填不能为空", trigger: "blur" },
        // ],
      },
      tableData: [],
      level: 1,
      areaName: "",
    };
  },
  created() {
    // 获取数据
    this.getData();
    this.bdmPermissions = this.permissions;
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  watch: {
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/basic-data-manage") {
        this.bdmPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      this.bdmPermissions = newVal;
    },
    addVisible(newBool, oldBool) {
      if (newBool == false) {
        this.value = "";
        // this.options = [];
      }
    },
    editVisible(newBool, oldBool) {
      if (newBool == false) {
        this.value = "";
        // this.options = [];
      }
    },
    value(newID, oldID) {
      this.editForm.parentId = newID;
    },
  },
  methods: {
    // 获取街道数据
    getData() {
      this.$axios
        .get("/village/subdistrict/page", {
          params: {
            page: this.query.pageIndex,
            limit: this.query.pageSize,
            parentId: 0,
          },
        })
        .then(({ data: res }) => {
          console.log("街道数据", res);
          if (res.code != 0) {
            return;
          }
          this.options = [];
          this.options1 = [];
          res.data.list.map((item) => {
            item.level = this.level = 1;
            item.show = false;
            item.area = item.name;
            item.children = [];
          });
          this.options = res.data.list;
          this.options1 = res.data.list;

          this.pageTotal = res.data.total || 0;
          this.tableData = [...res.data.list];
          console.log(this.tableData);
        })
        .catch((err) => {});
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getData();
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getData();
    },
    // 新增
    handleIncrease() {
      this.addForm.id = "0";
      this.addForm.level = "0";
      this.addVisible = true;
      this.areaName = "街道";
      this.addForm.subLevel = 0;
      this.show1 = false;
      this.show2 = false;
      this.options = this.options1;
    },
    // 新增子类
    increaseRow(index, row) {
      console.log(index, row);
      this.addForm.id = row.id;
      this.addForm.level = row.level;
      this.addVisible = true;
      if (row.parentId == 0) {
        this.areaName = "社区";
        this.addForm.subLevel = 1;
        this.show1 = true;
        this.show2 = false;

        this.options = this.options1;
      } else {
        this.areaName = "小区";
        this.addForm.subLevel = 2;
        this.show1 = true;
        this.show2 = false;

        this.options = this.options1.find((item) => {
          return row.parentId == item.id;
        }).children;
      }
      // if (row.parentId == 0) {
      //   this.options = this.tableData;
      // } else {
      //   this.options = this.tableData.find(item => {
      //     return row.parentId == item.id;
      //   }).children;
      // }
    },
    // 停用
    handleStop(index, row) {
      console.log(index, row);
      // 二次确认
      this.$confirm("确定要停用吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.editForm.level = row.level;

          // this.editForm.enableStatus = "1";
          // this.editForm.deleteStatus = row.deleteStatus;
          this.editForm.id = row.id;
          this.editForm.memo = row.memo;
          this.editForm.name = row.name;
          this.editForm.parentId = row.parentId;
          this.editForm.enableStatus = 1;
          this.editForm.subLevel = row.level - 1;
          this.saveEdit();
        })
        .catch(() => {});
    },
    // 启用
    handleEnable(index, row) {
      // 二次确认
      this.$confirm("确定要启用吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.editForm.level = row.level;

          // this.editForm.enableStatus = "0";
          // this.editForm.deleteStatus = row.deleteStatus;
          this.editForm.id = row.id;
          this.editForm.memo = row.memo;
          this.editForm.name = row.name;
          this.editForm.parentId = row.parentId;
          this.editForm.enableStatus = 0;
          this.editForm.subLevel = row.level - 1;
          this.saveEdit();
        })
        .catch(() => {});
    },
    // 保存新增
    saveIncrease() {
      console.log(this.addForm);
      this.$axios
        .post("/village/subdistrict", {
          parentId: this.addForm.id,
          name: this.addForm.name,
          memo: this.addForm.memo,
          subLevel: this.addForm.subLevel,
          // enableStatus: this.addForm.enableStatus,
          // deleteStatus: this.addForm.deleteStatus
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            return;
          }
          this.$message.success("新增成功");
          if (this.addForm.level == 1 || this.addForm.level == 2) {
            this.getNextData(this.addForm);
            // this.getData();
          } else if (this.addForm.level == 0) {
            this.getData();
          }
          this.addVisible = false;
          console.log(res);
          this.addForm = {
            name: "",
            memo: "",
            // enableStatus: "0",
            // deleteStatus: "0"
          };
          this.getData();
        })
        .catch((err) => {});
    },
    handleDelete(index, row) {
      console.log(index, row);
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.$axios
            .delete(`/village/subdistrict/${row.id}`)
            .then(({ data: res }) => {
              if (res.code != 0) {
                return;
              }
              this.$message.success("删除成功");
              if (row.level == 3) {
                this.getData();
              } else if (row.level == 1 || row.level == 2) {
                var { parentId: id, level } = row;
                this.getNextData({ id, level });
              }
            })
            .catch((err) => {});
        })
        .catch(() => {});
    },
    handleRow(index, row) {
      console.log(index, row);
      if (row.show) {
        index++;
        if (row.level < 3) {
          if (row.show) {
            var length = row.children.length;
            function myMap(array) {
              array.map((item) => {
                if (item.show) {
                  item.show = false;
                  length += item.children && item.children.length;
                  return myMap(item.children);
                }
              });
            }
            myMap(row.children);
            this.tableData.splice(index, length);
            row.show = false;
          } else {
            row.children.forEach((value) => {
              this.tableData.splice(index, 0, value);
              index++;
            });
            row.show = true;
          }
        }
      } else {
        this.getNextData(row).then(() => {
          index++;
          if (row.level < 3) {
            if (row.show) {
              var length = row.children.length;
              function myMap(array) {
                array.map((item) => {
                  if (item.show) {
                    item.show = false;
                    length += item.children && item.children.length;
                    return myMap(item.children);
                  }
                });
              }
              myMap(row.children);
              this.tableData.splice(index, length);
              row.show = false;
            } else {
              row.children.forEach((value) => {
                this.tableData.splice(index, 0, value);
                index++;
              });
              row.show = true;
            }
          }
        });
      }
    },
    // 获取社区&小区数据
    getNextData(row) {
      console.log(row);
      return this.$axios
        .get("/village/subdistrict/page", {
          params: {
            parentId: row.id,
          },
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            return;
          }
          if (row.level == 2) {
            this.level = 3;
          }
          if (row.level == 1) {
            this.level = 2;
          }
          res.data.list.map((item) => {
            item.level = this.level;
            item.show = false;
            item.area = item.name;
            if (this.level <= 2) {
              item.children = [];
            }
          });
          row.children = res.data.list;
          console.log(this.tableData, row);
          this.tableData.some((item) => {
            if (item.id == row.id) {
              item.children = row.children;
              return true;
            }
          });

          // this.options = row.children;
        })
        .catch((err) => {});
    },
    // 编辑操作
    handleEdit(index, row) {
      console.log(index, row);
      if (row.subLevel == 0) {
        this.areaName = "街道";
        this.editForm.subLevel = 0;
        this.show1 = false;
        this.show2 = false;
      } else if (row.subLevel == 1) {
        this.areaName = "社区";
        this.editForm.subLevel = 1;
        this.show1 = false;
        this.show2 = true;

        this.options = this.options1;
      } else if (row.subLevel == 2) {
        this.areaName = "小区";
        this.editForm.subLevel = 2;
        this.show1 = false;
        this.show2 = true;

        this.options1.find((item) => {
          var res = item.children.find((val) => {
            return row.parentId == val.id;
          });
          console.log(res);
          if (res) {
            this.options = res.children;
          }
        });
      }
      this.editForm.level = row.level;
      this.editVisible = true;
      this.getEditData(row.id);
    },
    getEditData(id) {
      return this.$axios
        .get(`/village/subdistrict/${id}`, {})
        .then(({ data: res }) => {
          console.log("编辑数据", res);
          if (res.code != 0) {
            return;
          }
          var {
            // deleteStatus,
            // enableStatus,
            id,
            memo,
            name,
            parentId,
          } = res.data;
          this.editForm = Object.assign(this.editForm, {
            // deleteStatus: deleteStatus.toString(),
            // enableStatus: enableStatus.toString(),
            id,
            memo,
            name,
            parentId,
          });
          var streetObj = this.options1.find((item) => {
            var res = item.children.find((val) => {
              return parentId == val.id;
            });
            return res;
          });
          console.log(streetObj);
          if (streetObj) {
            this.options = streetObj.children;
          }

          // return res.parentId == item.id;
          // console.log(res);
          // if (res) {
          //   this.options = res.children;
          // }

          this.value = parentId;
        });
    },
    // 保存编辑
    saveEdit() {
      this.$axios
        .put("/village/subdistrict", {
          // deleteStatus: this.editForm.deleteStatus,
          // enableStatus: this.editForm.enableStatus,
          id: this.editForm.id,
          memo: this.editForm.memo,
          name: this.editForm.name,
          parentId: this.editForm.parentId,
          subLevel: this.editForm.subLevel,
          enableStatus: this.editForm.enableStatus,
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            return this.$message.error(res.msg);
          }
          this.$message.success("操作成功");
          console.log(this.editForm);
          if (this.editForm.level == 1) {
            this.getData();
          } else if (this.editForm.level == 2 || this.editForm.level == 3) {
            var { parentId: id, level } = this.editForm;
            this.getNextData({ id, level });
            this.getData();
          }
          this.editVisible = false;
        })
        .catch((err) => {});
    },
  },
};
</script>
<style lang="scss">
.handle-box {
  margin-bottom: 20px;
}
.space {
  width: 20px;
  display: inline-block;
}
.arrow-width {
  width: 14px;
  display: inline-block;
}
</style>
